//
//  YewenCollegeCtrl.m
//  jobClient
//
//  Created by 小细菌 on 2021/3/9.
//  Copyright © 2021 YL1001. All rights reserved.
//

#import "YewenCollegeCtrl.h"
#import "PlayListContainer.h"
#import "YewenPdfView.h"
#import "YewenAudioView.h"
#import "LearnProgressHelper.h"

@interface YewenCollegeCtrl () {
    __weak ELAudioClass *audioManager;
    BOOL _isShowed4G;
}
@property (nonatomic, strong) YewenCollegeViewModel *viewModel;
@property (nonatomic, strong) YewenAudioView *audioView;
@property (nonatomic, strong) YewenPdfView *pdfView;
@property (nonatomic, strong) PlayListContainer *container;
@property (nonatomic, strong) LearnProgressHelper *progressHelper;

@property (nonatomic, strong) dispatch_source_t gcdTimer;
@property (nonatomic, assign) UIBackgroundTaskIdentifier bgTask;
@property (nonatomic, assign) BOOL isCheckingAuth;//是否正在验证

@end

@implementation YewenCollegeCtrl
@dynamic viewModel;


- (void)dealloc
{
    NSLog(@"%@ -- dealloc",self);
    [self stopTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.progressHelper = [[LearnProgressHelper alloc] init];
    
    id traget = self.navigationController.interactivePopGestureRecognizer.delegate;
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc] initWithTarget:traget action:nil];
    [self.view addGestureRecognizer:pan];
    
    GXLog(@"\n\n\n******我进到业问大学啦********\n config:\n%@",[APPCONFIG.training mj_JSONObject]);
    [self addObserver];
}
-(void)addObserver{
    [[NSNotificationCenter defaultCenter] addObserver:self
            selector:@selector(appWillEnterForeground)
            name:UIApplicationWillEnterForegroundNotification
            object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].idleTimerDisabled=YES;
    
    Media_info *media = self.viewModel.yewenModel.media_info;
    NSInteger type = media.media_type.intValue;
    if(type == 4) _pdfView.url = media.media_src;
    else if(type == 3) _audioView.imgUrl = _worksList.course.course_img;
    
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    int type = self.viewModel.yewenModel.media_info.media_type.intValue;
    if(type != 3 ) [ELAudioBottomView managerPlayer].showView = NO;
    
    if(APPCONFIG.training.projectId.intValue == 0 && type == 2) //知识库进来的,保存进度
        [self.progressHelper savelocalPlayProgress:self.viewModel.currentTime
                                         articleId:self.viewModel.article_id
                                      progressType:LearnProgressTypeVideo];
    [self.player pause];
}

- (void)gx_setupUI{
    __weak typeof(self) weakSelf = self;
    self.container =  [[PlayListContainer alloc] init];
    _container.projectId = _projectId;
    _container.isfromKnowledge = _isfromKnowledge;
    _container.view.frame = CGRectMake(0, ScreenWidth/16*9, ScreenWidth, ScreenHeight  - ScreenWidth/16*9 - (iphoneX?40.0:0));
    _container.model = self.worksList;
    _container.itemClick = ^(NSIndexPath* indexPath){
        [weakSelf itemClicked:indexPath];
    };
    [self addChildViewController:_container];
    [self.view addSubview:_container.view];
        
    _audioView = [[[NSBundle mainBundle] loadNibNamed:@"YewenAudioView" owner:self options:nil] lastObject];;
    [self.playerView addSubview:_audioView];
    _audioView.imgUrl = self.worksList.course.course_img;
    _audioView.hidden = YES;
    [_audioView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _audioView.backClick = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    _pdfView = [[YewenPdfView alloc] initWithFrame:self.playerView.bounds];
    [self.playerView addSubview:_pdfView];
    [_pdfView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _pdfView.hidden = YES;
    _pdfView.backClick = ^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
    
    
    
}

-(void)alertGotoHNAccessAuth{
    
    NSString *msg = @"应政策要求，需要前往指定程序进行验证，学习过程中不可退出、长时间暂停或将程序切换到后台挂起,学习过程中会随机弹出认证，请不要分心离开！";
    UIAlertController *warnAlert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:msg preferredStyle:UIAlertControllerStyleAlert];

    [warnAlert addAction:[UIAlertAction actionWithTitle:@"去验证" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        self.isCheckingAuth = YES;
        if (self.viewModel.isGetAccessLink) {//直接去获取链接
            [self checkGetHNAccessLinkWithUserAccessToken:self.viewModel.userAccessToken traceId:self.viewModel.traceId];
        }else{
            [self checkGetHNAccessToken];
        }
    }]];
//    [warnAlert addAction:[UIAlertAction actionWithTitle:@"完成验证" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        //去验证结果
//        [self verifyCheckCode];
//    }]];
//    [warnAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [self popViewController];
//    }]];
    [self presentViewController:warnAlert animated:YES completion:nil];
}
#pragma mark - ---------->会到前台，尝试去直接去验证
- (void)appWillEnterForeground {
    NSLog(@"-------------------应用已返回前台");
    if (self.isCheckingAuth) {
        [self verifyCheckCode];
    }
    // 执行UI更新、重新加载数据等操作
}
// 河南培训
- (void)checkGetHNAccessToken{
//    self.viewModel.playLastProgress = [self.progressHelper localPlayProgressWithArticleId:self.viewModel.article_id progressType:LearnProgressTypeVideo];
    NSString *process = @"";
    if (self.viewModel.currentTime <= 0) {//说明是还没开始播放，刚进来，第一次进来，获取到的播放进度要拿从接口返回
        process = [NSString stringWithFormat:@"%ld",self.viewModel.playLastProgress];
    }else{//已经播放了，可以直接拿到播放器播放进度
        process = [NSString stringWithFormat:@"%ld",self.viewModel.currentTime];
    }
    ELTrainingRequestModel *model = [[ELTrainingRequestModel alloc] init];
    [model getHeNanTokenWithCourseId:_worksList.course.course_id courseName:_worksList.course.course_name projectId:APPCONFIG.training.projectId worksId:self.viewModel.article_id process:process];
    [HPNetworking postWithModel:model succeed:^(id _Nullable result) {
        NSLog(@"---%@",result);
        /*获取token------ 然后调用v6.01/hnjg_training_busi/getAccessLink验证链接
        拿到跳转小程序的 信息 ，
        然后小程序验证完成返回APP 在调用验证结果接口*/
        NSDictionary *dict = result;
        if (DictIsNotEmpty(dict) && ((NSString *)dict[@"code"]).intValue == 200) {
            NSString *userAccessToken = dict[@"data"][@"userAccessToken"];
            NSString *traceId = dict[@"data"][@"traceId"];
            self.viewModel.userAccessToken = userAccessToken;
            self.viewModel.traceId = traceId;
            [self checkGetHNAccessLinkWithUserAccessToken:userAccessToken traceId:traceId];
        }else {
            toast(dict[@"status_desc"]);
            if (DictIsNotEmpty(dict) && ((NSString *)dict[@"code"]).intValue == 1103) {//没有按顺序观看
                [self popViewController];
            }else{
                [self alertGotoHNAccessAuth];
            }
        }
    } failure:^(NSString * _Nullable error) {
        NSLog(@"---%@",error);
        toast(@"网络异常");
        [self alertGotoHNAccessAuth];
    }];
}

// 河南培训
- (void)checkGetHNAccessLinkWithUserAccessToken:(NSString *)userAccessToken traceId:(NSString *)traceId{
    NSString *process = @"";
    if (self.viewModel.currentTime <= 0) {//说明是还没开始播放，刚进来，第一次进来，获取到的播放进度要拿从接口返回
        process = [NSString stringWithFormat:@"%ld",self.viewModel.playLastProgress];
    }else{//已经播放了，可以直接拿到播放器播放进度
        process = [NSString stringWithFormat:@"%ld",self.viewModel.currentTime];
    }
    ELTrainingRequestModel *model = [[ELTrainingRequestModel alloc] init];
    [model getHeNanAccessLinkWithUserAccessToken:userAccessToken traceId:traceId playProcess:process worksId:self.viewModel.article_id];
    [HPNetworking postWithModel:model succeed:^(id _Nullable result) {
        NSLog(@"---%@",result);
        /*获取token------ 然后调用v6.01/hnjg_training_busi/getAccessLink验证链接
        拿到跳转小程序的 信息 ，
        然后小程序验证完成返回APP 在调用验证结果接口*/
        NSDictionary *dict = result;
        if (DictIsNotEmpty(dict) && ((NSString *)dict[@"code"]).intValue == 200) {
            NSString *hnjgCode = dict[@"data"][@"hnjgCode"];
            if (hnjgCode.intValue == 0) {
                NSString *wxAppId = dict[@"data"][@"hnjgWxUserName"];
                NSString *verifyPage = dict[@"data"][@"miniAppPath"];
                NSString *checkCode = dict[@"data"][@"checkCode"];
                NSString *traceId = dict[@"data"][@"traceId"];
                self.viewModel.traceId = traceId;
                self.viewModel.checkCode = checkCode;
                [self pushToWechatMiniProgramWithUserName:wxAppId path:verifyPage];
            }else{
                self.viewModel.isGetAccessLink = NO;
                [self alertGotoHNAccessAuth];
            }
        }else {
            toast(dict[@"status_desc"]);
            [self alertGotoHNAccessAuth];
        }
    } failure:^(NSString * _Nullable error) {
        NSLog(@"---%@",error);
        toast(@"网络异常");
        [self alertGotoHNAccessAuth];
    }];
}

#pragma mark - ---------->跳转到小程序
-(void)pushToWechatMiniProgramWithUserName:(NSString *)userName path:(NSString *)path{
    WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
    launchMiniProgramReq.userName = userName;  //拉起的小程序的username
    launchMiniProgramReq.path = path;    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
    launchMiniProgramReq.extDic = @{@"user":@"yl1001"};
    launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
    [WXApi sendReq:launchMiniProgramReq completion:^(BOOL success) {
        
        NSLog(@"------------------->%d",success);
//        [self alertGotoHNAccessAuth];
    }];
}
-(void)verifyCheckCode{
    if (!self.isCheckingAuth) {
        return;
    }
    self.isCheckingAuth = NO;//只能放进来一个
    if (StringIsEmpty(self.viewModel.traceId) || StringIsEmpty(self.viewModel.checkCode)) {
        toast(@"您还未验证，请点击去验证");
        [self alertGotoHNAccessAuth];
        return;
    }
    ELTrainingRequestModel *model = [[ELTrainingRequestModel alloc] init];
    [model verifyeHeNanCheckCodeResultWithTraceId:self.viewModel.traceId checkCode:self.viewModel.checkCode];
    [HPNetworking postWithModel:model succeed:^(id _Nullable result) {
        NSLog(@"---%@",result);
        /*获取token------ 然后调用v6.01/hnjg_training_busi/getAccessLink验证链接
        拿到跳转小程序的 信息 ，
        然后小程序验证完成返回APP 在调用验证结果接口*/
        NSDictionary *dict = result;
        if (DictIsNotEmpty(dict) && ((NSString *)dict[@"code"]).intValue == 200) {
            NSString *userAccessToken = dict[@"data"][@"userAccessToken"];
//            NSString *checkCode = result[@"data"][@"checkCode"];
            NSString *checkTokenInterval = dict[@"data"][@"checkTokenInterval"];
            self.viewModel.userAccessToken = userAccessToken;
            self.viewModel.checkCode = @"";
            self.viewModel.checkTokenInterval = checkTokenInterval;//验证时间点
            self.viewModel.isGetAccessLink = YES;
            if (self.viewModel.checkTokenInterval.intValue > 0) {
                [self startTimer];//开启定时器
            }
            [self.viewModel.continueSubject sendNext:nil];
        }else {
            toast(dict[@"status_desc"]);
            self.viewModel.isGetAccessLink = NO;
            [self alertGotoHNAccessAuth];
        }
    } failure:^(NSString * _Nullable error) {
        NSLog(@"---%@",error);
        toast(@"网络异常");
        self.viewModel.isGetAccessLink = NO;
        [self alertGotoHNAccessAuth];
    }];
        
}

    
- (void)gx_bindViewModel{
    @weakify(self)
    
    [self.viewModel.onBackClickListener subscribeNext:^(id x){
        @strongify(self);
        [self popViewController];
    }];
    [self.viewModel.pauseSubject subscribeNext:^(id  _Nullable x) {
        [self.player pause];
    }];
    
    HudShow;
    [[self.viewModel.loadFinishedSubject timeout:10 onScheduler:[RACScheduler mainThreadScheduler]]  subscribeNext:^(YewenMediaDetailModel* yewenModel) {
        @strongify(self)
        HudHide;
        if(APPCONFIG.training.projectId.intValue == 0 && yewenModel.media_info.media_type.intValue == 2)
            self.viewModel.playLastProgress = [self.progressHelper localPlayProgressWithArticleId:self.viewModel.article_id progressType:LearnProgressTypeVideo];
     
        //self.container.playTitle = yewenModel.title;
        self.container.playTitle = _worksList.course.course_name;
        [self configUI:yewenModel];
    } error:^(id error){
        HudHide;
        [self alertWithTitle:@"提示" message:[error isKindOfClass:NSString.class]?error:@"网络开了小差" cancelButtonTitle:@"知道了" otherButtonTitles:nil handler:^(UIAlertAction* action){
            [self popViewController];
        }];
    }];

    [[self.viewModel.onFinishListener deliverOnMainThread] subscribeNext:^(id x){
        @strongify(self);
        [self.progressHelper savelocalPlayProgress:0 articleId:self.viewModel.article_id progressType:LearnProgressTypeVideo];
        self.viewModel.playLastProgress = 0;
    }];
    
//    [self.viewModel beginRequest];
}

- (void)configUI:(YewenMediaDetailModel* )yewenModel{
    
    self.viewModel.videoUrl = nil;
    self.pdfView.hidden = self.audioView.hidden= YES;
    int type = yewenModel.media_info.media_type.intValue;
    if(type == 2){
        if([Manager shareMgr].networkStutus == AFNetworkReachabilityStatusReachableViaWWAN){
            if (_isShowed4G || [Manager shareMgr].didShow4GToastPlay) {
                [self playVedio:yewenModel];
            }else {
                _isShowed4G = YES;
                NSString* s = GXString(@"您正在使用3G/4G/5G网络，继续观看将消耗%@流量", [self getVedioSizeByUrl:yewenModel.media_info.media_src]);
                [self alertWithTitle:@"提示" message:s cancelButtonTitle:@"取消" otherButtonTitles:@[@"继续"] handler:^(UIAlertAction *action){
                    if (action.style == UIAlertActionStyleCancel) {
                        [self popViewController];
                    }else{
                        [Manager shareMgr].didShow4GToastPlay = YES;
                        [self playVedio:yewenModel];
                    }
                }];
            }
        }else{
            [self playVedio:yewenModel];
        }
    }else if(type == 3){
        ELAudioPlayModel* audioModel = ELAudioPlayModel.new;
        audioModel.article_id = self.viewModel.article_id;
        audioModel.audio_url = yewenModel.media_info.media_src;
        audioModel.article_title = yewenModel.media_info.title;
        audioModel.audio_time = yewenModel.media_info.media_duration_sub;
        _audioView.model = audioModel;
        _audioView.hidden = NO;
    }else if(type == 4){
        [self freeAudioPlayer];
        _pdfView.hidden = NO;
        _pdfView.webTitle = yewenModel.media_info.title;
        _pdfView.url = yewenModel.media_info.media_src;
    }else{
        toast(@"%@", GXString(@"数据异常\nmedia_type=%@",yewenModel.media_info.media_type));
    }
}

- (void)playVedio:(YewenMediaDetailModel* )yewenModel{
    
    
    [self freeAudioPlayer];
    self.viewModel.videoTitle = yewenModel.title;
    self.viewModel.videoUrl = yewenModel.media_info.media_src;
    if (APPCONFIG.training.project_source.intValue == 60 && !self.viewModel.isComplete) {//河南监管
//        [self.viewModel.pauseSubject sendNext:nil];//先暂停，验证一下
        self.viewModel.isGetAccessLink = NO;
        [self alertGotoHNAccessAuth];
    }else{
        [self.viewModel.continueSubject sendNext:nil];
    }
}

- (void)itemClicked:(NSIndexPath*) indexPath{
    [self stopTimer];//定时器销毁，重新开始下一轮学习打卡
    self.viewModel.isGetAccessLink = NO;
    
    self.viewModel.videoUrl = nil;
    [self.viewModel authComplete];
    self.pdfView.hidden = self.audioView.hidden = YES;
    
    NSString* article_id = self.worksList.section_works[indexPath.section].works_list[indexPath.row].works_id;
    YewenCollegeViewModel *vm = [[YewenCollegeViewModel alloc]  initWithArticleId:article_id groupId:self.viewModel.group_id];
    vm.isComplete = self.isfromKnowledge;
    self.viewModel = vm;
    [self gx_bindViewModel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [self.viewModel beginRequest];
    });
}



- (void)freeAudioPlayer{
    if (![Manager shareMgr].audioManager){
        [[Manager shareMgr].audioManagerBack free];
        [Manager shareMgr].audioManager = [[ELAudioClass alloc] init];
        [[Manager shareMgr].audioManager remoteControlEventHandler];
    }
    audioManager = [Manager shareMgr].audioManager;
    [audioManager free];
    [audioManager.player pause];
}


- (void)popViewController{

    NSLog(@"退出页面业问大学页面popViewController");
    if ([[Manager getCurrentVC] isKindOfClass: NSClassFromString(@"ApprovedViewController").class] ||
        [[Manager getCurrentVC] isKindOfClass: NSClassFromString(@"ELPictureVerifyViewController").class]) { //这个是乐山打卡的页面
        [[Manager getCurrentVC] dismissViewControllerAnimated:NO completion:^(){
            [self popViewController];
        }];
    }else{
//        NSMutableArray* array = [Manager getCurrentVC].navigationController.viewControllers.mutableCopy;
//        if ([array.lastObject isKindOfClass:NTFaceAliveCtrl.class]) {
//            [array removeLastObject];
//            [array removeLastObject];
//            [[Manager getCurrentVC].navigationController setViewControllers:array.copy animated:YES];
//        }else{
//            [[Manager getCurrentVC].navigationController popViewControllerAnimated:YES];
//        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)startTimer{
    [self stopTimer]; // 避免重复启动
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.gcdTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 开启后台任务
    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self.player pause];//禁止后台学习
    }];
        
    // 设置触发时间（700秒后）
    dispatch_time_t startTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.viewModel.checkTokenInterval.intValue * NSEC_PER_SEC));
    // 设置单次触发（repeats=0）
    dispatch_source_set_timer(self.gcdTimer, startTime, 0, 5 * NSEC_PER_SEC);
        
    __weak typeof(self) weakSelf = self;
    dispatch_source_set_event_handler(self.gcdTimer, ^{
        if (!weakSelf) return;
        [weakSelf timerMethod];
        dispatch_source_cancel(weakSelf.gcdTimer); // 单次触发后销毁
    });
    dispatch_resume(self.gcdTimer);
}
-(void)stopTimer{
    if (self.gcdTimer) {
        dispatch_source_cancel(self.gcdTimer);
        self.gcdTimer = nil;
    }
    if (self.bgTask != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }
}
-(void)timerMethod {
    // 执行任务（需切回主线程更新UI）
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"------------时间已到，执行任务--------%@",self.viewModel.checkTokenInterval);
        [self.player pause];//先暂停，验证一下
        [self alertGotoHNAccessAuth];
    });
}

 
@end
